package com.scy.videocomponent.config;

import com.scy.videocomponent.vo.NodeVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author wuhao
 */
@Configuration
public class DataConfig {

    @Value("${staticLocals}")
    private String[] staticLocations;

    public static List<NodeVO> list;

    private static List<String> types = Arrays.asList("mp4","mkv","avi","rmvb");

    @PostConstruct
    private void init(){
        list = new ArrayList<>();
        for(String staticLocation:staticLocations){
            if(staticLocation.indexOf("file://") == 0){
                String temp = staticLocation.replace("file://","");
                File file = new File(temp);
                if(file.exists() && file.isDirectory()){
                    list.add(method(file,null));
                }
            }
        }
    }

    private NodeVO method(File file,String root){
        NodeVO nodeVO = new NodeVO();
        nodeVO.setText(file.getName());
        //是不是文件夹
        if(file.isDirectory()){
            List<NodeVO> voList = new ArrayList<>();
            //获取子文件列表
            File[] files = file.listFiles();
            //遍历子文件列表
            for (File file1:files) {
                String prefix = "";
                if(root == null){
                    prefix = "/";
                }else{
                    prefix = root + file.getName() + "/";
                }
                //递归调用
                NodeVO temp = method(file1,prefix);
                //对子文件的可播放的或文件夹添加到列表中
                if(temp != null){
                    voList.add(temp);
                }
            }
            nodeVO.setList(voList);
        }else {
            //获取后缀
            String suffix = file.getName().substring(file.getName().lastIndexOf(".")+1);
            //是不是可以支持播放的类型
            if(types.contains(suffix)){
                nodeVO.setUrl(root+file.getName());
            }else{
                nodeVO = null;
            }
        }
        return nodeVO;
    }
}
